import React, { useEffect, useState } from 'react';

import { Pagination, Table } from 'antd';

import { Storage } from '@/utils/storage';
import { useStores } from '@/stores';
import { MARK_COLUMN_OBJ, MARK_FIELD_DEFAULT, MARK_LAYER_COLUMNS, UNIT_TO_M } from '@/utils/constant';
import { markSlitColumns, markSlitData } from '@/utils/tool';
import { markingBackT } from '@/typings/global';
import { observer } from 'mobx-react-lite';

// 图层批号对应的---小卷的column

export interface MarkingTableProps {
  list: markingBackT[];
  changePage: () => void;
}

export const TableList: React.FC<MarkingTableProps> = (props: MarkingTableProps) => {
  const { markingStore } = useStores();
  const [tableData, setTableData] = useState<markingBackT[]>([]);

  useEffect(() => {
    initHandle();
  }, []);

  // 初始化的处理
  const initHandle = () => {
    const isStorage = Storage.get('markingField');
    if (isStorage) {
      markingStore.setMarkField(isStorage.checkedList, MARK_COLUMN_OBJ);
    } else {
      markingStore.setMarkField(MARK_FIELD_DEFAULT, MARK_COLUMN_OBJ);
    }
  };

  useEffect(() => {
    const tableData = props.list;
    setTableData(tableData);
  }, [props.list]);

  /**
   * 缺陷卡片页数改变事件
   * @param page
   */
  const onChangePage = async page => {
    markingStore.table.currentPage = page;
    props.changePage();
  };

  const expandedRowRender = (record, index, indent, expanded, markingStore) => {
    // 将数据处理成子列表的形式
    const baseData = markSlitData(record);
    // 对数据按照model进行整合，并且对其相关数据进行合并单元格操作
    const { columns, tableData } = markSlitColumns(baseData, markingStore.markingFieldChecked);

    return expanded && <Table columns={columns as any} dataSource={tableData} pagination={false} scroll={{ y: 500 }} bordered />;
  };

  return (
    <>
      <div className="marking-table">
        <Table
          className="marking-table-antd"
          columns={MARK_LAYER_COLUMNS}
          expandable={{
            expandedRowRender: (record, index, indent, expanded) => expandedRowRender(record, index, indent, expanded, markingStore),
            defaultExpandedRowKeys: []
          }}
          dataSource={tableData}
          scroll={{ y: 700 }}
          pagination={false}
        />
        <Pagination
          className="papgation"
          showSizeChanger={false}
          current={markingStore.table.currentPage}
          total={markingStore.table.total}
          onChange={onChangePage}
          showTotal={() => `总数:${markingStore.table.total}`}
          pageSize={markingStore.table.pageSize || 16}
        />
      </div>
    </>
  );
};

export default observer(TableList);
